package com.dmzapp.api.servlet;

import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import com.dmzapp.api.service.RedisAndDBService;
import com.dmzapp.api.util.Constant;
import com.dmzapp.api.vo.OutRecord;

/**
 * Servlet implementation class for Servlet: UserInOutDetailHandler
 * 
 */
public class UserOutDetailHandler extends com.dmzapp.api.servlet.DMZSerlvet {
    static final long serialVersionUID = 1L;
    private ObjectMapper mapper = new ObjectMapper();

    /*
     * (non-Java-doc)
     * 
     * @see javax.servlet.http.HttpServlet#HttpServlet()
     */
    public UserOutDetailHandler() {
        super();
    }

    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response) {

        // TODO: 分页查询, out数据还没有
        try {
            String username = (String) request.getAttribute("u");
            int start = Integer.valueOf(request.getParameter("start"));
            Map<String, Object> responseMap = new HashMap<String, Object>();
            List<OutRecord> outlist = RedisAndDBService.getUseroutcomeList(username);
            
            if (outlist != null && !outlist.isEmpty()) {
                int total = outlist.size();
                Collections.sort(outlist);
                int end = total - start < Constant.APP_LIST_PAGE_SIZE ? total : start + Constant.APP_LIST_PAGE_SIZE;
                List<OutRecord> sub = outlist.subList(start, end);

                responseMap.put("outlist", sub);
                responseMap.put("listSize", total);
                responseMap.put("amount", RedisAndDBService.getUserAmount(username));
                responseMap.put("rest", RedisAndDBService.getUserRest(username));
                responseMap.put("server_time", Calendar.getInstance().getTimeInMillis());
                mapper.writeValue(response.getWriter(), responseMap);
            } else {
                mapper.writeValue(response.getWriter(), "nothing");
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}